﻿using Core.Framework.Model.Common;
using Core.IBusiness.ISDK;
using SDK.ApiService;
using System;
using System.Collections.Generic;
using System.Text;
using Core.Framework.Util;
using Core.Framework.Redis;
using Core.Framework.Redis.Queue_Helper;
using Core.IBusiness.ISDK.Model;
using Core.IBusiness.IUserModule;
using Core.DataAccess.Model.Project.Queue;
using System.Linq;
using Microsoft.AspNetCore.Http;

namespace Core.Business.SDKService
{
    public class SMS : ISMS
    {

        IRedisHelper iRedis;
        private ApiProjectInfo iProjectInfo;

        /// <summary>
        /// 获取token
        /// </summary>
        private string getCodeToken {
            get
            {
                return Guid.NewGuid().ToString().Replace("-", "");
            }
        }

        public SMS(IRedisHelper _iRedis, IHttpContextAccessor _httpContextAccessor)
        {
            iRedis = _iRedis;
            iProjectInfo = (ApiProjectInfo)_httpContextAccessor.HttpContext.Items["ApiProjectInfo"];
        }

        public MethodResult Plus(string toPhone, string content, string sign, MsgTypeEnum MsgTypeEnum)
        {
            try
            {

                sign = "iTool";

                SMSService sms = new SMSService(new SMSParameter
                {
                    toPhone = toPhone,
                    context = content,
                    sign = sign,
                    templateId = (int)MsgTypeEnum
                });

                var result = sms.Send();


                if (result.result == 0)
                {
                    return new MethodResult { IsFinished = true };
                }
                else
                {
                    return new MethodResult { IsFinished = false, Discription = result.errMsg };
                }
            }
            catch (Exception e)
            {
               return new MethodResult { IsFinished = false, Discription = e.Message };
            }
        }

        public MethodResult<string> UserLogin(string toPhone, string sign)
        {
            var token = this.getCodeToken;

            var result = this.SendUserSMS(toPhone, sign, token, MsgTypeEnum.登陆);

            if (result.IsFinished)
            {
                // 5分钟内有效
                iRedis.Set(RedisQueueHelperParameter.SMSMessageCode + token, result.Date.ToString(), TimeSpan.FromMinutes(5));

                return new MethodResult<string> { Date = token, IsFinished = true };
            }
            else
            {
                return new MethodResult<string> { Discription = result.Discription, IsFinished = true };
            }

        }

        public MethodResult<int> UserPay(string toPhone, string sign)
        {
            var token = this.getCodeToken;
            return this.SendUserSMS(toPhone, sign, token, MsgTypeEnum.付款);
        }

        public MethodResult<int> UserReg(string toPhone, string sign)
        {
            var token = this.getCodeToken;

            using (var context = new ProjectSocketContext())
            {
                var userInfo = context.ProjectModuleUser.Where(a => a.Phone == toPhone && a.ProjectToken == iProjectInfo.Token).FirstOrDefault();

                if (userInfo != null && userInfo?.Id > 0)
                {
                    return new MethodResult<int> { Date = 0, Discription = "用户已存在", IsFinished = false };
                }
            };

            return this.SendUserSMS(toPhone, sign, token, MsgTypeEnum.注册);
        }

        public MethodResult<int> UserUpdatePassword(string toPhone, string sign)
        {

            using (var context = new ProjectSocketContext())
            {
                var userInfo = context.ProjectModuleUser.Where(a => a.Phone == toPhone && a.ProjectToken == iProjectInfo.Token).FirstOrDefault();

                if (userInfo == null || userInfo?.Id < 1)
                {
                    return new MethodResult<int> { Date = 0, Discription = "用户不存在", IsFinished = false };
                }
            };

            var token = this.getCodeToken;

            return this.SendUserSMS(toPhone, sign, token, MsgTypeEnum.找回密码);
        }

        public MethodResult<int> UserBingPhone(string toPhone, string sign)
        {
            var token = this.getCodeToken;
            return this.SendUserSMS(toPhone, sign, token, MsgTypeEnum.绑定手机);
        }





        #region Common

        private MethodResult<int> SendUserSMS(string toPhone, string sign, string token, MsgTypeEnum MsgTypeEnum)
        {

            sign = "iTool";

            var retryKey = RedisQueueHelperParameter.SMSMessageCodeRetry + toPhone + (int) MsgTypeEnum;

            try
            {
                

                var resultAsync = iRedis.GetAsync(retryKey);

                // 30S之内重复发送验证
                if (!string.IsNullOrWhiteSpace(resultAsync.Result))
                {
                    return new MethodResult<int> { IsFinished = false, Discription = "接口过载，请稍后再试。" };

                    // 检测是否存在验证码
                    //var value = iRedis.Get<string>(RedisQueueHelperParameter.SMSMessageCode + resultAsync.Result);

                    // 如果验证码存在直接返回
                    //if (!string.IsNullOrWhiteSpace(value))
                    //{
                        
                    //}
                }

                int smscode = this.SmsCode();

                SMSService sms = new SMSService(new SMSParameter
                {
                    toPhone = toPhone,
                    context = smscode.ToString(),
                    sign = sign,
                    templateId = (int)MsgTypeEnum
                });

                var result = sms.Send();

                if (result.result == 0)
                {
                    // 发送成功
                    // 5S之内不可重复发送
                    // 分布式验证
                    iRedis.Set(retryKey, token, TimeSpan.FromSeconds(30));
                    return new MethodResult<int> { IsFinished = true, Date = smscode };
                }
                else
                {
                    return new MethodResult<int> { IsFinished = false, Discription = result.errMsg };
                }
            }
            catch (Exception e)
            {
                return new MethodResult<int> { IsFinished = false, Discription = e.Message };
            }
        }

        private int SmsCode() { return new Random().Next(100000, 999999); }
        #endregion
    }
}
